package com.cgah

import com.cgah.exceptions.CustomerNotFoundException
import javax.jws.WebMethod
import javax.jws.WebResult
import javax.jws.WebParam

class CustomerService {//implements com.cgah.api.CustomerService {
//    static scope = "session"
    static expose=['cxfjax']
    static transactional = true

    // W-3: Expose the three Grails service methods created for S-1, S-2, and S-3 via SOAP/WSD
    // for testing
/*    @WebResult(name="zresult")
    @WebMethod(operationName="test")
    def blah() {
        return "blah";
    }*/


    def countOfCustomers() {
        return Customer.count()
    }

    def list(def params) {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        return Customer.list(params);
    }



/*
    // W-3: Expose the three Grails service methods created for S-1, S-2, and S-3 via SOAP/WSD
    @WebResult(name="Customer")
    @WebMethod(operationName="create")
*/
    def create(def params) {
        def customerInstance = new Customer()
        customerInstance.properties = params
        return customerInstance
    }


    // W-3: Expose the three Grails service methods created for S-1, S-2, and S-3 via SOAP/WSD
    @WebResult(name="Customer")
    @WebMethod(operationName="save")
    public Customer save(@WebParam(name="customer") Customer customerInstance) {
        if (!customerInstance.createdDate) {
            customerInstance.createdDate = new Date();
        }
        return customerInstance.save(flush: true);
    }

    def getCustomerById(def id) throws CustomerNotFoundException {
        def c = Customer.get(id);
        if (null == c) {
            throw new CustomerNotFoundException("Customer with id: " + id + " does not exists.");
        }
        return c;
    }

    def deleteCustomerById(def id) throws CustomerNotFoundException {
        def customerInstance = this.getCustomerById(id);
        if (null != customerInstance && customerInstance.canDelete()) {
            UserRole.removeAll(customerInstance);
            customerInstance.delete(flush: true)
            return true;
        }
        return false;
    }

    def updateCustomerWithParams(def params) throws CustomerNotFoundException {
        def customerInstance = this.getCustomerById(params.id) // Customer.get(params.id)
        if (customerInstance) {
            if (params.version && customerInstance.version > params.version.toLong()) {
                    customerInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'customer.label', default: 'Customer')] as Object[], "Another user has updated this Customer while you were editing")
            } else {
                customerInstance.properties = params
                if (!customerInstance.hasErrors()) {
                    customerInstance = this.save(customerInstance)
                }
            }
        }
        return customerInstance;
    }


}
